package com.lock.springbootdistributedlock.repository;

import com.lock.springbootdistributedlock.entity.DistributedLock;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface DistributedLockRepository extends JpaRepository<DistributedLock, String> {

    @Query(value = "SELECT * FROM distributed_lock WHERE lock_key = ?1 FOR UPDATE", nativeQuery = true)
    Optional<DistributedLock> findByLockKeyForUpdate(String lockKey);

    @Modifying
    @Query(value = "INSERT INTO distributed_lock (lock_key, lock_value, create_time) VALUES (?1, ?2, NOW())", nativeQuery = true)
    int tryAcquireLock(String lockKey, String lockValue);
}
